#include "cw32l010_adc.h"
#include "cw32l010_gpio.h"
#include "cw32l010_sysctrl.h"
#include "bsp_adc.h"

void bsp_adc_init(void)
{
    __SYSCTRL_ADC_CLK_ENABLE();
    __SYSCTRL_GPIOA_CLK_ENABLE();

	
    ADC_InitTypeDef ADC_InitStructure = {0};

	ADC_DeInit();
	
    // CW32L010_UserManual_CN_V1.1.pdf page:505
    ADC_InitStructure.ADC_ClkDiv = ADC_Clk_Div1;
    ADC_InitStructure.ADC_ConvertMode = ADC_ConvertMode_Once; // 单次采样
    ADC_InitStructure.ADC_SQREns = ADC_SqrEns0to0;            // 单通道
    ADC_InitStructure.ADC_IN0.ADC_InputChannel = ADC_InputCH2;
    ADC_InitStructure.ADC_IN0.ADC_SampTime = ADC_SampTime390Clk;

    ADC_InitStructure.ADC_IN0.ADC_InputChannel = 0x0f;
    ADC_Init(&ADC_InitStructure);

    ADC_ClearITPendingAll();

#if 0
    ADC_ITConfig(ADC_IT_EOC, ENABLE);
    NVIC_EnableIRQ(ADC_IRQn);
#endif
    // ADC使能
}

// 这里返回的是VDDA上的电压
unsigned short get_adc_value(void)
{
    ADC_Enable();
    REGBITS_SET(CW_ADC->CR, ADC_CR_BGREN_Msk);
    ADC_SoftwareStartConvCmd(ENABLE);
    while (!(CW_ADC->ISR & ADC_ISR_EOC_Msk))
        ;
    ADC_ClearITPendingBit(ADC_IT_EOC);
    ADC_Disable();
    REGBITS_CLR(CW_ADC->CR, ADC_CR_BGREN_Msk);
    return (*(uint16_t *)0x001007D2) * 4095 / ADC_GetConversionValue(0);
}

#if 0
void ADC_IRQHandler(void)
{
    /* USER CODE BEGIN */
	
	volatile uint8_t gFlagIrq;
    gFlagIrq = CW_ADC->ISR;
    CW_ADC->ICR = 0x00;

    /* USER CODE END */
}
#endif